package com.cby.android.base.localsocket

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.cby.android.base.R
import android.net.LocalSocketAddress

import android.net.LocalSocket
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.TextView
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.lang.Exception


/**
 * @description: MyLocalSocketClientActivity
 * @author: ChenBaoYang
 * @createDate: 2022/3/24 10:58 上午
 */
class MyLocalSocketClientActivity : AppCompatActivity() {


    private val tag = "chenby"

    private lateinit var showTv: TextView

    private lateinit var handler: MyHandler



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_local_socket_client)
        showTv = findViewById(R.id.tv_show)
        handler = MyHandler(this)
    }

    fun connectServer(view: View) {
        handler.sendEmptyMessage(handler.msgConnect)
    }

    fun updateText(text: String) {
        showTv.append(text)
    }

    fun readWriteData(view: View) {
        handler.sendEmptyMessage(handler.msgReadOrWrite)
    }




}

class ReadThread(private val socket: LocalSocket, private val handler: MyHandler) : Thread() {

    override fun run() {
        // 写法一
        val input = socket.inputStream
        val isr = InputStreamReader(input, "UTF-8")
        //专程BufferReader
        val reader = BufferedReader(isr)
        //获取数据转成字符串
        var result: String? = ""
        var info: String? = ""
        while (reader.readLine().also { info = it } != null) {
            //循环读取客户端的信息
            result += info
            Log.i("chenby", "ClientActivity read:$result")
        }
        val message = Message()
//        val data = Bundle()
//        data.putString("key", info)
        message.what = handler.msgUpdateUi
        message.obj = result
        handler.sendMessage(message)

    }
}


class MyHandler(private val activity: MyLocalSocketClientActivity) : Handler(Looper.getMainLooper()) {

    private lateinit var socket: LocalSocket
    val msgConnect = 0x111
    val msgReadOrWrite = 0x112
    val msgUpdateUi = 0x113

    override fun handleMessage(msg: Message) {
        when(msg.what){
            msgConnect -> {
                connect()
            }
            msgReadOrWrite -> {
                writeData("测试数据");
            }
            msgUpdateUi -> {
                activity.updateText(msg.obj as String)
            }
        }
    }

    private fun connect() {
        try{
            socket = LocalSocket() //创建LocalSocket，模拟客户端
            val addressServer = "com.cby.server.local.socket"
            val address = LocalSocketAddress(
                addressServer,
                LocalSocketAddress.Namespace.ABSTRACT
            )
            socket.connect(address) //连接MyLocalSocketServerActivity
            //writeData("测试数据");
        }catch (e:Exception){
            Log.i("chenby","e = "+e.message)
        }

    }


    private fun writeData(cmdString: String): Boolean {
        val cmd: ByteArray = cmdString.toByteArray()
        val len = cmd.size
        try {
            // 读取数据
            ReadThread(socket,this).start()

            val out = socket.outputStream
            out.write(cmd, 0, len)
            activity.updateText(String(cmd))
            Log.i("chenby", "ClientActivity write " + String(cmd))
        } catch (ex: IOException) {
            Log.e("chenby", "ClientActivity write error:" + ex.fillInStackTrace())
            return false
        }finally {
            socket.shutdownInput()
            socket.shutdownOutput()
        }
        return true
    }
}